<?php

/*
 * Edit by xinli
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */
namespace app\admin\controller;

use cmf\controller\AdminBaseController;

use think\facade\Log;
use app\user\model\UserModel;
use app\portal\model\UserLevelDefineModel;
use app\portal\model\UserPromoteRelationModel;
use app\portal\model\UserRewardDetailModel;

use think\db\Query;

/**
 * Description of PromoteController
 *
 * @author PC
 */
class PromoteController extends AdminBaseController
{

    /**
     * 推广二维码背景图片设置
     * @adminMenu(
     *     'name'   => '推广二维码背景图片设置',
     *     'parent' => 'admin/Promote/Index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '推广二维码背景图片设置',
     *     'param'  => ''
     * )
     */
    public function promoteQrcodeBg()
    {
        $promote = cmf_get_option('promote');
        $this->assign("promote", $promote);

        $promoteQrcodeBg = [];
        $promoteQrcodeBg['promote_qrcode_bg']['value'] = isset($promote['promote_qrcode_bg']) ? $promote['promote_qrcode_bg'] : "";
        $promoteQrcodeBg['promote_qrcode_bg']['type'] = "image2";
        $this->assign("array_item", $promoteQrcodeBg);

        return $this->fetch('promote_qrcode_bg');
    }

    /**
     * 推广二维码背景图片提交
     * @adminMenu(
     *     'name'   => '推广二维码背景图片提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '推广二维码背景图片提交',
     *     'param'  => ''
     * )
     */
    public function addPromoteQrcodeBgPost()
    {
        if ($this->request->isPost()) {
            $promote = $this->request->param('promote/a');
            cmf_set_option('promote', $promote);
            $this->success(lang('EDIT_SUCCESS'), '');
        }
    }

    /**
     * 邀请奖励设置
     * @adminMenu(
     *     'name'   => '邀请奖励设置',
     *     'parent' => 'admin/Promote/Index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '邀请奖励设置',
     *     'param'  => ''
     * )
     */
    public function inviteReward()
    {
        $inviteReward = cmf_get_option('invite_reward');
        if ($inviteReward == null) {
            $inviteReward = [
                "invite_num_1" => 5,
                "invite_num_2" => 5,
                "invite_num_3" => 5,
                "invite_num_4" => 5,
                "invite_num_5" => 5,
            ];
        }
        $this->assign("invite_reward", $inviteReward);
        return $this->fetch('invite_reward');
    }

    /**
     * 邀请奖励设置提交
     * @adminMenu(
     *     'name'   => '邀请奖励设置提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '邀请奖励设置提交',
     *     'param'  => ''
     * )
     */
    public function updateInviteRewardPost()
    {
        if ($this->request->isPost()) {
            $inviteReward = $this->request->param('invite_reward/a');
            cmf_set_option('invite_reward', $inviteReward);
            $this->success(lang('EDIT_SUCCESS'), '');
        }
    }

    /**
     * 等级奖励设置
     * @adminMenu(
     *     'name'   => '等级奖励设置',
     *     'parent' => 'admin/Promote/Index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '等级奖励设置',
     *     'param'  => ''
     * )
     */
    public function userLevelDefine()
    {
        $userLevelDefineModel = new UserLevelDefineModel();
        $userLevelDefineArray = $userLevelDefineModel->select();
        $this->assign("level_define_array", $userLevelDefineArray);
        return $this->fetch('level_define');
    }

    /**
     * 等级奖励设置提交
     * @adminMenu(
     *     'name'   => '等级奖励设置提交',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '等级奖励设置提交',
     *     'param'  => ''
     * )
     */
    public function userLevelDefinePost()
    {
        if ($this->request->isPost()) {
            $inviteReward = $this->request->param('level_define_post/a');
            
            $userLevelDefineModel = new UserLevelDefineModel();
            $userLevelDefineModel->startTrans();
            try {
                foreach ($inviteReward as $key => $value) {
                    // Log::info('[ inviteReward ]' . json_encode($value));
                    $userLevelDefineModel->where('id', $value['id'])
                        ->update(['condition_invite' => $value['condition_invite'], 'condition_team' => $value['condition_team'], 'reward_percent' => $value['reward_percent']*100, 'update_time' => time(),'medal_id'=>$value['medal_id']]);
                }
                $userLevelDefineModel->commit();
            } catch (\Exception $e) {
                $userLevelDefineModel->rollback();
                $this->error(lang('EDIT_FAIL'));
            }
            $this->success(lang('EDIT_SUCCESS'), '');
        }
    }
    
    /**
     * 邀请用户明细
     * @adminMenu(
     *     'name'   => '邀请用户明细',
     *     'parent' => 'admin/Promote/Index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '邀请用户明细',
     *     'param'  => ''
     * )
     */
    public function inviteUserDetail()
    {
        $filter = $this->request->param();
        $userPromoteRelationModel = new UserPromoteRelationModel();    
        $userRewardDetailModel = new UserRewardDetailModel();    
        $query = $userPromoteRelationModel->alias('upr');
        $query->join('cmf_user u', 'upr.user_id = u.id');
        $query->leftJoin('cmf_user_promote_relation upr_parent', 'upr_parent.user_id = upr.parent_id');
        $query->leftJoin('cmf_user u_parent', 'u_parent.id = upr.parent_id');
        $fields = 'u.id, u.user_nickname, u.avatar, u.score, u.mobile, upr.update_time, 
                    u_parent.id as parent_id, u_parent.user_nickname as parent_nickname, u_parent.mobile as parent_mobile';

        $datas = $query->field($fields)
            ->where(function (Query $query) use ($filter) {

                $userId = empty($filter['user_id']) ? 0 : intval($filter['user_id']);
                if (!empty($userId)) {
                    $query->where('u.id', $userId);
                }

                $mobile = empty($filter['mobile']) ? 0 : intval($filter['mobile']);
                if (!empty($mobile)) {
                    $query->where('u.mobile', $mobile);
                }

                $parentId = empty($filter['parent_id']) ? 0 : intval($filter['parent_id']);
                if (!empty($parentId)) {
                    $query->where('upr.parent_id', $parentId);
                }

                $query->where('upr.promote_status', 1);
            })
            ->order('upr.update_time', 'DESC')
            ->paginate(20);


        // 循环$datas，查询每个用户的下级用户数和贡献的星链石总数
        foreach ($datas as &$item) {
            $item['directPromoteCount'] = $userPromoteRelationModel->where('parent_id', $item['id'])->where('promote_status', 1)->count();
            $item['rewardCount'] = $userRewardDetailModel->where('user_id', $item['id'])->sum('reward_count');
            $item['avatar'] = cmf_get_image_url($item['avatar']);
            $userId = $item['id'];
            $item['indirectPromoteCount'] = $userPromoteRelationModel->where('parent_id', 'in', function($query) use ($userId) {
                $query->name('user_promote_relation')->where('parent_id', $userId)->where('promote_status', 1)->field('user_id');
            })->where('promote_status', 1)->count();
        }

        $this->assign('parent_id', isset($filter['parent_id']) ? $filter['parent_id'] : '');
        $this->assign('user_id', isset($filter['user_id']) ? $filter['user_id'] : '');  
        $this->assign('mobile', isset($filter['mobile']) ? $filter['mobile'] : '');

        $this->assign('page', $datas->render());
        $this->assign('items', $datas);
        return $this->fetch('invite_detail');
    }

    /**
     * 推荐奖励详情
     * @adminMenu(
     *     'name'   => '推荐奖励详情',
     *     'parent' => 'admin/Promote/Index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '推荐奖励详情',
     *     'param'  => ''
     * )
     */
    public function rewardDetail()
    {
        $filter = $this->request->param();
        $startTime = isset($filter['start_time']) ? $filter['start_time'] : '';
        $endTime = isset($filter['end_time']) ? $filter['end_time'] : '';
        if (!empty($startTime) && !empty($endTime) && $startTime >= $endTime) {
            // $this->error("截止日期需大于起始日期");        
            $tempTime = $filter['start_time'];
            $filter['start_time'] = $filter['end_time'];
            $filter['end_time'] = $tempTime;
        }

        $userRewardDetailModel = new UserRewardDetailModel();   
        $query = $userRewardDetailModel->alias('urd');
        $query->leftJoin('cmf_user u_provoide', 'urd.provide_user_id = u_provoide.id');
        $fields = 'u_provoide.*, urd.*';

        $datas = $query->field($fields)
            ->where(function (Query $query) use ($filter) {
                $startTime = empty($filter['start_time']) ? 0 : strtotime($filter['start_time']);
                $endTime   = empty($filter['end_time']) ? 0 : strtotime($filter['end_time']);
                if (!empty($startTime) && !empty($endTime) && $startTime >= $endTime) {
                    $tempTime = $startTime;
                    $startTime = $endTime;
                    $endTime = $tempTime;
                }
                if (!empty($startTime)) {
                    $query->where('urd.create_time', '>=', $startTime);
                }
                if (!empty($endTime)) {
                    $endTime = $endTime + 86400;
                    $query->where('urd.create_time', '<=', $endTime);
                }

                $provideUserId = empty($filter['provide_user_id']) ? 0 : intval($filter['provide_user_id']);
                if (!empty($provideUserId)) {
                    $query->where('urd.provide_user_id', $provideUserId);
                }

                $userId = empty($filter['user_id']) ? 0 : intval($filter['user_id']);
                if (!empty($userId)) {
                    $query->where('urd.user_id', $userId);       
                }         
            })
            ->order('urd.create_time', 'DESC')
            ->paginate(20);

        $this->assign('start_time', isset($filter['start_time']) ? $filter['start_time'] : '');
        $this->assign('end_time', isset($filter['end_time']) ? $filter['end_time'] : '');
        $this->assign('provide_user_id', isset($filter['provide_user_id']) ? $filter['provide_user_id'] : '');
        $this->assign('user_id', isset($filter['user_id']) ? $filter['user_id'] : '');

        $this->assign('page', $datas->render());
        $this->assign('items', $datas);
        return $this->fetch('reward_detail');
    }
}
